<template>
  <div class="articles-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2>文章管理</h2>
        <p>管理博客文章，包括创建、编辑、删除等操作</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="$router.push('/admin/articles/create')">
          <el-icon><Plus /></el-icon>
          新建文章
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-section">
      <el-card>
        <el-form :model="searchForm" inline>
          <el-form-item label="搜索">
            <el-input
              v-model="searchForm.keyword"
              placeholder="搜索文章标题"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="分类">
            <el-select
              v-model="searchForm.category"
              placeholder="选择分类"
              clearable
              :filterable="true"
            >
              <el-option
                v-for="category in categories"
                :key="category.id"
                :label="category.name"
                :value="category.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="searchForm.status"
              placeholder="选择状态"
              clearable
            >
              <el-option label="已发布" value="published" />
              <el-option label="草稿" value="draft" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 文章列表 -->
    <div class="articles-list">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>文章列表</span>
            <div class="header-actions">
              <el-button
                type="danger"
                size="small"
                :disabled="!selectedArticles.length"
                @click="batchDelete"
              >
                批量删除
              </el-button>
            </div>
          </div>
        </template>

        <el-table
          v-loading="loading"
          :data="articles"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          
          <el-table-column label="封面" width="80">
            <template #default="{ row }">
              <el-image
                v-if="row.cover"
                :src="getCoverUrl(row.cover)"
                :preview-src-list="[getCoverUrl(row.cover)]"
                fit="cover"
                style="width: 60px; height: 40px; border-radius: 4px;"
              />
              <div
                v-else
                style="width: 60px; height: 40px; background: #f5f7fa; border-radius: 4px; display: flex; align-items: center; justify-content: center;"
              >
                <el-icon><Picture /></el-icon>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="title" label="标题" min-width="200">
            <template #default="{ row }">
              <div class="article-title">
                <span>{{ row.title }}</span>
                <el-tag v-if="row.is_top" type="warning" size="small">置顶</el-tag>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="category.name" label="分类" width="100" />
          
          <el-table-column prop="status" label="状态" width="80">
            <template #default="{ row }">
              <el-tag :type="row.status === 'published' ? 'success' : 'info'">
                {{ row.status === 'published' ? '已发布' : '草稿' }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="view_count" label="浏览量" width="80" />
          
          <el-table-column
            label="时间"
            width="140"
          >
            <template #default="{ row }">
              <span v-if="row.status === 'published'">{{ formatDate(row.published_at) }}</span>
              <span v-else>{{ formatDate(row.created_at) }}</span>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button
                type="primary"
                size="small"
                @click="editArticle(row.id)"
              >
                编辑
              </el-button>
              <el-button
                type="success"
                size="small"
                @click="previewArticle(row.id)"
              >
                预览
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="deleteArticle(row.id)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="pagination.current_page"
            v-model:page-size="pagination.per_page"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Picture } from '@element-plus/icons-vue'
import { articleApi, categoryApi } from '@/api/admin'

const router = useRouter()

// 搜索表单
const searchForm = ref({
  keyword: '',
  category: null,
  status: ''
})

// 文章列表
const articles = ref([])
const categories = ref([])
const selectedArticles = ref([])
const loading = ref(false)

// 分页
const pagination = ref({
  current_page: 1,
  per_page: 20,
  total: 0
})

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 获取文章列表
const fetchArticles = async () => {
  // 保证类型一致
  if (typeof searchForm.value.category === 'string' && searchForm.value.category !== '') {
    searchForm.value.category = Number(searchForm.value.category)
  }
  loading.value = true
  try {
    const params = {
      page: pagination.value.current_page,
      per_page: pagination.value.per_page,
      keyword: searchForm.value.keyword,
      status: searchForm.value.status
    }
    if (searchForm.value.category !== null && searchForm.value.category !== '') {
      params.category = searchForm.value.category
    }
    const response = await articleApi.getArticles(params)
    articles.value = response.data || []
    pagination.value = {
      current_page: response.meta.current_page || 1,
      per_page: response.meta.per_page || 20,
      total: response.meta.total || 0
    }
  } catch (error) {
    console.error('获取文章列表失败:', error)
    ElMessage.error('获取文章列表失败')
  } finally {
    loading.value = false
  }
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    const response = await categoryApi.getCategories()
    categories.value = response.data || []
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  pagination.value.current_page = 1
  fetchArticles()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    keyword: '',
    category: null,
    status: ''
  }
  pagination.value.current_page = 1
  fetchArticles()
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedArticles.value = selection
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.value.per_page = size
  pagination.value.current_page = 1
  fetchArticles()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.value.current_page = page
  fetchArticles()
}

// 编辑文章
const editArticle = (id) => {
  router.push(`/admin/articles/edit/${id}`)
}

// 预览文章
const previewArticle = (id) => {
  window.open(`/post/${id}`, '_blank')
}

// 删除文章
const deleteArticle = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这篇文章吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await articleApi.deleteArticle(id)
    ElMessage.success('删除成功')
    fetchArticles()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除文章失败:', error)
      ElMessage.error('删除文章失败')
    }
  }
}

// 批量删除
const batchDelete = async () => {
  if (!selectedArticles.value.length) {
    ElMessage.warning('请选择要删除的文章')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedArticles.value.length} 篇文章吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里应该调用批量删除API
    const ids = selectedArticles.value.map(article => article.id)
    // await articleApi.batchDelete(ids)
    
    ElMessage.success('批量删除成功')
    selectedArticles.value = []
    fetchArticles()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

const getCoverUrl = (path) => {
  if (!path) return ''
  if (/^https?:\/\//.test(path)) return path
  const base = import.meta.env.VITE_API_BASE_URL?.replace(/\/$/, '') || ''
  return path.startsWith('storage/')
    ? `${base}/${path}`
    : `${base}/storage/${path}`
}

// 组件挂载
onMounted(() => {
  fetchCategories()
  fetchArticles()
})
</script>

<style scoped lang="scss">
.articles-page {
  background: #fafbfc;
  min-height: 100vh;
  padding: 32px 0;

  .page-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 24px;
  }

  .page-title {
    font-size: 24px;
    font-weight: 700;
    color: #222;
  }

  .search-section {
    margin-bottom: 24px;
  }

  .articles-list {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .article-title {
      display: flex;
      align-items: center;
      gap: 8px;

      span {
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }

    .pagination-wrapper {
      margin-top: 24px;
      display: flex;
      justify-content: center;
    }
  }
}

@media (max-width: 768px) {
  .articles-page {
    padding: 16px 0;
  }
  .articles-list {
    border-radius: 12px;
    padding: 12px;
  }
  .page-title {
    font-size: 18px;
  }
}
</style> 